package com.chen.Dome6lock;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Account {
    private String cardId;
    private double balance;
    private final Lock lk = new ReentrantLock();// 创建锁对象,final保护锁

    public void drawmoney(double money) {
        String name = Thread.currentThread().getName();
        lk.lock();
        //判断余额是否充足
        try {
            if (balance >= money) {
                System.out.println(name + "取款成功，取款金额：" + money);
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                balance -= money;
                System.out.println("余额为：" + balance);
            } else {
                System.out.println(name + "取款失败，余额不足");
            }
        } finally {//finally语句块，保证锁一定释放，即使出现异常也会执行
            lk.unlock();
        }
    }

}
